﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Studio77.PopBall.Util;
using System.Windows.Media;
using Studio77.PopBall.Core;
using Studio77.PopBall.Entities;
using System.Windows.Controls.Primitives;
using Studio77.PopBall.Utils;
using OpenXLive.Features;
using OpenXLive;
using Microsoft.Phone.Tasks;
using System.Diagnostics;
using CN.SmartMad.Ads.WindowsPhone.WPF;
using System.Windows.Threading;
using System.Windows.Media.Imaging;

namespace Studio77.PopBall.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage Instance = null;

        private int currentScore = 0;

        private int currentStageIndex = 1;

        private int currentTarget = 0;

        /// <summary>
        /// 游戏状态 0-未开始 1-游戏中 2-游戏结束 3-暂停
        /// </summary>
        private int gameStatus = 0;

        private bool isStageClear = false;

        private List<ToggleButton> toolButtons = new List<ToggleButton>();

        public bool isToolShow = false;
        public int CurrentSelectToolType { get; set; }

        DispatcherTimer mokaAdsSwitchTimer;
        int currentMokaAdIndex = 0;
        int totalMokaAdCount = 2;

        public GamePage()
        {
            InitializeComponent();
            Instance = this;

            toolButtons.Add(btnBall1);
            toolButtons.Add(btnBall2);
            toolButtons.Add(btnBall3);
            toolButtons.Add(btnBall4);
            toolButtons.Add(btnBall5);
            initToolButtonStatus();
            CurrentSelectToolType = 0;

            //魔卡广告切换Timer
            mokaAdsSwitchTimer = new DispatcherTimer();

            //获取间隔参数
            int intervalSec = 30;
            string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
            if (!int.TryParse(secStr, out intervalSec))
            {
                intervalSec = 30;
            }

            mokaAdsSwitchTimer.Interval = TimeSpan.FromSeconds(intervalSec);
            mokaAdsSwitchTimer.Tick += mokaAdsSwitchTimer_Tick;
            mokaAdsSwitchTimer.Start();

            bool useSmartmad = true;
            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if (usemokaStr == "1" || usemokaStr == "2")
            {
                if (StageManager.Instance.TurnMoka)
                {
                    //移动moka到最前面，而且不显示亿动
                    LayoutRoot.Children.Remove(imgBanner);
                    LayoutRoot.Children.Add(imgBanner);
                    useSmartmad = false;
                }
                StageManager.Instance.TurnMoka = !StageManager.Instance.TurnMoka;
                currentMokaAdIndex = 0;
                switchMokaAdImage();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {

            }


            if (useSmartmad)
            {
                if (StageManager.Instance.AdType == 1)
                {
                    InitSmartMadAd();
                }
            }
            else
            {
                gridMsnAd.Visibility = System.Windows.Visibility.Collapsed;
            }

        }

        /// <summary>
        /// 更新魔卡广告的banner
        /// </summary>
        private void switchMokaAdImage()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(@"\Images\banner" + (currentMokaAdIndex + 1).ToString() + ".jpg", UriKind.RelativeOrAbsolute));
            this.imgBanner.Source = bitmap;
        }

        void mokaAdsSwitchTimer_Tick(object sender, EventArgs e)
        {
            currentMokaAdIndex++;
            currentMokaAdIndex = currentMokaAdIndex % totalMokaAdCount;
            switchMokaAdImage();
        }


        private void initToolButtonStatus()
        {
            foreach (var item in toolButtons)
            {
                item.IsChecked = false;
                if (StageManager.Instance.MagicBallCount > 0)
                {
                    item.IsEnabled = true;
                }
                else
                {
                    item.IsEnabled = false;
                }
            }
            this.gridTooltip1.Visibility = System.Windows.Visibility.Visible;
            this.gridTooltip2.Visibility = System.Windows.Visibility.Collapsed;
            this.txtMagicBallCount.Text = StageManager.Instance.MagicBallCount.ToString();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (isToolShow)
            {
                btnCloseToll_Click(null, null);
            }
            else if (gameStatus == 1)
            {
                gameStatus = 3;
                StoryboardShowPause.Begin();
            }
            else if (gameStatus == 3)
            {
                gameStatus = 1;
                StoryboardHidePause.Begin();
            }
            e.Cancel = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //保存游戏历史数据

            if (gameStatus == 1 || gameStatus == 3)
            {
                //保存游戏记录
                SavedGameData gameData = new SavedGameData();
                gameData.CurrentScore = currentScore;
                gameData.StageIndex = currentStageIndex;
                gameData.GameData = gameCanvas.GetGameData();
                StageManager.Instance.SaveData = gameData;
            }
            else if (gameStatus == 2)
            {
                //清空历史记录
                StageManager.Instance.SaveData = null;
            }


        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (StageManager.Instance.IsPlaySound)
            {
                this.btnSoundOn.Visibility = System.Windows.Visibility.Visible;
                this.btnSoundOff.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                this.btnSoundOn.Visibility = System.Windows.Visibility.Collapsed;
                this.btnSoundOff.Visibility = System.Windows.Visibility.Visible;
            }

            //播放背景音乐
            AudioPlayHelper.PlayBackground();
            if (gameStatus == 0)
            {
                string isNewGame = "1";
                NavigationContext.QueryString.TryGetValue("IsNewGame", out isNewGame);

                if (isNewGame == "1")
                {
                    this.imageStageClearFlag.Visibility = System.Windows.Visibility.Collapsed;
                    isStageClear = false;
                    isToolShow = false;
                    currentStageIndex = 1;
                    UpdateTarget(currentStageIndex);
                    //新游戏，从关卡1开始
                    gameCanvas.InitGame();

                    this.startView.Show(currentStageIndex, currentTarget);
                    this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(2700);
                    this.StoryboardShowGameCanvas.Begin();
                    this.gameStatus = 1;
                    this.txtHighScore.Text = StageManager.Instance.HighScore.ToString();

                }
                else
                {
                    isToolShow = false;
                    //继续游戏，从上次的记录点开始
                    if (StageManager.Instance.SaveData != null)
                    {
                        currentStageIndex = StageManager.Instance.SaveData.StageIndex;
                        currentScore = StageManager.Instance.SaveData.CurrentScore;
                        UpdateTarget(currentStageIndex);

                        //载入游戏进度
                        gameCanvas.ContinueGame(StageManager.Instance.SaveData.GameData);

                        this.startView.Show(currentStageIndex, currentTarget);
                        this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(2700);
                        this.StoryboardShowGameCanvas.Begin();
                        this.gameStatus = 1;
                        this.txtHighScore.Text = StageManager.Instance.HighScore.ToString();
                        this.txtCurrentScore.Text = currentScore.ToString();

                        isStageClear = false;
                        this.imageStageClearFlag.Visibility = System.Windows.Visibility.Collapsed;
                        if (currentScore >= currentTarget)
                        {
                            isStageClear = true;
                            this.imageStageClearFlag.Visibility = System.Windows.Visibility.Visible;
                        }
                    }
                }
            }
        }

        private void UpdateTarget(int stageIndex)
        {
            //设置目标
            currentTarget = ScoreHelper.GetTargetScore(currentStageIndex);
            this.txtTarget.Text = currentTarget.ToString();
            this.txtStage.Text = currentStageIndex.ToString();
        }

        internal void AddScore(int score)
        {
            currentScore += score;
            this.StoryboardAddScore.Begin();
            this.txtCurrentScore.Text = currentScore.ToString();

            if (StageManager.Instance.HighScore < currentScore)
            {
                StageManager.Instance.HighScore = currentScore;
                this.txtHighScore.Text = StageManager.Instance.HighScore.ToString();
            }

            //判断是否过关
            if (currentScore >= currentTarget)
            {
                ClearStage();
            }
        }

        private void ClearStage()
        {
            if (!isStageClear)
            {
                isStageClear = true;
                //显示通过标志
                this.imageStageClearFlag.Visibility = System.Windows.Visibility.Visible;
                this.StoryboardStageClear.Begin();

                //送一个魔法球
                this.StoryboardAddMagicBall.Begin();
                StageManager.Instance.MagicBallCount++;
                this.txtMagicBallCount.Text = StageManager.Instance.MagicBallCount.ToString();

                //音效
                SoundManager.PlayEffect(SoundManager.stageClear);
            }
        }

        public void NoEliminate()
        {
            if (currentScore < currentTarget)
            {
                //GameOver
                SoundManager.PlayEffect(SoundManager.failed);
                this.StoryboardGameOver.Begin();
                gameStatus = 2;
                MyDispatcherTimer tempTimer = new MyDispatcherTimer();
                tempTimer.Interval = TimeSpan.FromMilliseconds(2500);
                tempTimer.Tick += (object ss, EventArgs ee) =>
                {
                    tempTimer.Stop();
                    //跳转到主界面
                    GotoMarketToComment();
                    this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
                };
                tempTimer.Start();
                //上传分数至排行榜
                Leaderboard lb = new Leaderboard(XLiveGameManager.CurrentSession, "5f3db983-d1fe-441b-8e3e-0603765b2220");
                lb.SubmitScoreCompleted += lb_SubmitScoreCompleted;
                lb.SubmitScore(this.currentScore);

            }
            else
            {
                //进行下一个关卡
                //this.StoryboardHideGameCanvas.Begin();
                isToolShow = false;
                this.StoryboardHideMagicBall.Begin();
                this.gameCanvas.Opacity = 0;
                (this.gameCanvas.RenderTransform as CompositeTransform).TranslateY = -800;
                currentStageIndex++;
                UpdateTarget(currentStageIndex);
                this.startView.Show(currentStageIndex, currentTarget);
                this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(2700);
                this.StoryboardShowGameCanvas.Begin();

                MyDispatcherTimer tempTimer = new MyDispatcherTimer();
                tempTimer.Interval = TimeSpan.FromMilliseconds(2000);
                tempTimer.Tick += (object ss, EventArgs ee) =>
                {
                    tempTimer.Stop();
                    gameCanvas.RestartGame();
                };
                tempTimer.Start();
                this.imageStageClearFlag.Visibility = System.Windows.Visibility.Collapsed;

                isStageClear = false;
            }
        }

        void lb_SubmitScoreCompleted(object sender, AsyncEventArgs e)
        {

        }

        internal void ShowScoreTip(int count)
        {
            this.txtSelectComment.Text = count + " 个球 " + ScoreHelper.GetScore(count) + " 分";
            this.StoryboardShowScoreComment.Begin();
        }

        public void HideToolArea()
        {
            this.txtMagicBallCount.Text = StageManager.Instance.MagicBallCount.ToString();
            btnCloseToll_Click(null, null);
        }

        private void btnCloseToll_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //关闭工具选择
            isToolShow = false;
            CurrentSelectToolType = 0;
            this.StoryboardHideMagicBall.Begin();
            SoundManager.PlayEffect(SoundManager.buttonClick);
        }

        private void btnMagicBall_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            isToolShow = true;
            initToolButtonStatus();
            this.StoryboardShowMagicBall.Begin();
            SoundManager.PlayEffect(SoundManager.buttonClick);
        }

        private void btnBall1_Click_1(object sender, RoutedEventArgs e)
        {
            //选择道具
            ToggleButton btn = (ToggleButton)sender;
            CurrentSelectToolType = toolButtons.IndexOf(btn) + 1;
            foreach (var item in toolButtons)
            {
                item.IsChecked = false;
            }
            btn.IsChecked = true;
            this.gridTooltip1.Visibility = System.Windows.Visibility.Collapsed;
            this.gridTooltip2.Visibility = System.Windows.Visibility.Visible;

            SoundManager.PlayEffect(SoundManager.buttonClick);
        }

        private void btnHome_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void btnSoundOn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //关闭音效
            StageManager.Instance.IsPlaySound = false;
            AudioPlayHelper.StopBackground();
            this.btnSoundOn.Visibility = System.Windows.Visibility.Collapsed;
            this.btnSoundOff.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnSoundOff_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //打开音效
            StageManager.Instance.IsPlaySound = true;
            AudioPlayHelper.PlayBackground();
            this.btnSoundOn.Visibility = System.Windows.Visibility.Visible;
            this.btnSoundOff.Visibility = System.Windows.Visibility.Collapsed;
        }

        /// <summary>
        /// 去市场评价
        /// </summary>
        private void GotoMarketToComment()
        {
            if (!StageManager.Instance.IsCommented && StageManager.Instance.LaunchCount > 15)
            {
                if (MessageBox.Show("喜欢我们的游戏吗？如果喜欢，请给我们一个五星好评吧，谢谢您对我们的支持", "去评分", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                    marketplaceReviewTask.Show();
                    StageManager.Instance.IsCommented = true;
                }
                else
                {
                    StageManager.Instance.LaunchCount = StageManager.Instance.LaunchCount + 1;
                    StageManager.Instance.IsCommented = true;
                }
            }
        }

        #region 亿动广告

        private void InitSmartMadAd()
        {
            //  实例化SmartMad Banner容器
            SMAdBannerView banner = new SMAdBannerView("90033299");
            //  设置Banner广告刷新过场动画类型(可选)
            banner.AdBannerAnimationType =
            SMAdBannerAnimationType.BANNER_ANIMATION_TYPE_FADEINOUT;
            //  设置Banner广告事件
            banner.AdBannerClicked += new EventHandler(banner_AdBannerClicked);
            banner.AdBannerWillExpand += new EventHandler(banner_AdBannerWillExpand);
            banner.AdBannerExpandClosed += new
            EventHandler(banner_AdBannerExpandClosed);
            banner.AdBannerReceived += new EventHandler(banner_AdBannerReceived);
            banner.AdBannerReceiveFailed += new
            EventHandler<SMAdEventCode>(banner_AdBannerReceiveFailed);
            banner.AdBannerPresentingScreen += new
            EventHandler<SMAdEventCode>(banner_AdBannerPresentingScreen);
            banner.AdBannerLeaveApplication += new
            EventHandler(banner_AdBannerLeaveApplication);
            banner.AppWillSuspendForAd += new
            EventHandler(banner_AppWillSuspendForAd);
            banner.AppWillResumeFromAd += new
            EventHandler(banner_AppWillResumeFromAd);
            banner.AdBannerDismissScreen += new
            EventHandler(banner_AdBannerDismissScreen);
            //  将Banner容器加入界面
            gridMsnAd.Children.Add(banner);
        }

        private void banner_AdBannerDismissScreen(object sender, EventArgs e)
        {

        }

        private void banner_AppWillResumeFromAd(object sender, EventArgs e)
        {

        }

        private void banner_AppWillSuspendForAd(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerLeaveApplication(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerPresentingScreen(object sender, SMAdEventCode e)
        {

        }

        private void banner_AdBannerReceiveFailed(object sender, SMAdEventCode e)
        {

        }

        private void banner_AdBannerReceived(object sender, EventArgs e)
        {
            //接收成功，隐藏微软广告
            Dispatcher.BeginInvoke(() =>
            {
                if (adControlMicrosoft != null)
                {
                    this.LayoutRoot.Children.Remove(adControlMicrosoft);
                    adControlMicrosoft = null;
                }
            });
        }

        private void banner_AdBannerExpandClosed(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerWillExpand(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerClicked(object sender, EventArgs e)
        {

        }

        #endregion

        private void imgBanner_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            if (currentMokaAdIndex == 0)
            {
                //跳转到魔卡幻想
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c035da4065183dbec79ffbe43fa11301ac619c2b8fdd723b692ae4b7915b3ce7", UriKind.Absolute);
            }
            else
            {
                //跳转到千魔斩
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=5fc22bb64e05cb93477f153d9d61cb409179c3036db5ba85446dde582ec3c345", UriKind.Absolute);
            }
            webBrowserTask.Show();
        }

        private void btnResume_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (gameStatus == 3)
            {
                gameStatus = 1;
                this.StoryboardHidePause.Begin();
            }
        }

        private void btnMainMenu_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.NavigationService.CanGoBack)
            {
                this.NavigationService.GoBack();
            }
            else
            {
                this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }
    }
}